<template>
  <el-row class="detail-row detail-card">
    <Title title="发布信息" font-size="16px" style="margin-bottom:18px;">
      <tipIcon :content="tipContent" use-html class="ml5"></tipIcon>
    </Title>
    <simpleEditTable
      ref="simpleEditTableRef"
      :get-order-info="getOrderInfo"
      :order-id="orderInfo.id"
      :publish-url="detailInfo.publishInfo?detailInfo.publishInfo.publishUrl:''"
      :is-edit="orderStatus === 1"
      :disabled="isFileDisabled || !isPublishAuth"
      v-model="tableData"
      :list-setting="listSetting"
      :is-link-required="isLinkRequired"
      :not-pick-platform="Boolean(!pickPlatformIds.includes(orderInfo.orderPlatformId) && orderInfo.orderPlatformId)"
      :header-check="detailInfo.publishInfo"
      :show-operate="true"
      @checkLink="handleCheckLink" />
  </el-row>
</template>

<script>
import { mapState } from 'vuex';
import Title from '@/components/Title';
import { hasRouteAuth } from '@/utils/permission';
import simpleEditTable from '@/components/Common/simpleEditTable.vue';
import { checkLink } from '@/api/publish';
import { showModal } from '@/utils/message';
import { linkRequiredCheck } from '@/api/order';
// 信息对比需要
export default {
  components: {
    Title, simpleEditTable
  },
  props: {
    orderInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    configureOrderInfo: {
      type: Object,
      default: () => {
        return null;
      }
    },
    detailInfo: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      tipContent: '发布链接可以不必填的情况<br>1、订单来源为达人个人引进<br>2、下单形式为“流量主”时<br>3、订单来源不为达人个人引进且下单形式通用设置配置发布链接非必填',
      isLinkRequired: undefined, // 用来获取通用设置里的发布链接是否必填
      pickPlatformIds: [3, 4, 5]// 微博、微信、小红书
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isFileDisabled() {
      return !hasRouteAuth('crm:orderList:publishInfo');
    },
    orderStatus() {
      // 订单状态： 0: 草稿中 1: 待发布 2: 待核算 3: 待审批 4: 待封账 5: 封账中 6: 已封账 7: 已完成
      return this.detailInfo.orderStatus || '';
    },
    isAllAdmin() { // 是否有全向权限
      const item = this.detailInfo ? this.detailInfo : {};
      const departmentId = item.attributionMatrixId;

      let cooperationDepartmentIds = []; // 协作部门ID
      if (item.orderInfo.cooperationDepartment && item.orderInfo.cooperationDepartment.length) {
        cooperationDepartmentIds = item.orderInfo.cooperationDepartment.map(i => i.id);
      }
      let departmentAuth = false; // 拥有部门全向编辑，当前登录的用户存在该条订单的部门中,或者协作部门中
      if (hasRouteAuth('crm:orderList:adminEdit')) {
        const currentDeptIds = this.userInfo.currentDeptIds || []; // 当前部门的所有id，比如：用户部门是 研发部->产品组，那么当前部门就是产品组
        const topDeptIds = this.userInfo.topDeptIds || []; // 顶级部门的id列表，比如：用户部门是 研发部->产品组，那么顶级部门就是研发部

        const departmentAry = currentDeptIds.concat(topDeptIds);
        departmentAuth = departmentAry.some(i => {
          return (i === departmentId) || cooperationDepartmentIds.includes(i);
        });
      }
      return departmentAuth || hasRouteAuth('crm:orderList:admin');
    },
    isPublishAuth() { // 发布权限
      /**
       * 发布权限 && （
       * 用户在该条订单的执行人中 ||
       * 用户为当前销售  ||
       * 部门全向编辑及部门符合要求 ||
       * 全向展示 ||
       * 如果执行人为空且部门符合要求）
       */
      if (this.userInfo.userName === '管理员') return true; // 管理员
      const item = this.detailInfo ? this.detailInfo : {};
      const orderOperator = item.orderInfo.orderOperator || []; // 执行人(资源侧加商务测)
      const departmentId = item.attributionMatrixId;
      let cooperationDepartmentIds = []; // 协作部门ID
      if (item.orderInfo.cooperationDepartment && item.orderInfo.cooperationDepartment.length) {
        cooperationDepartmentIds = item.orderInfo.cooperationDepartment.map(i => i.id);
      }

      const isOperatorAuth = orderOperator ? orderOperator.some(i => {
        return i.id === this.userInfo.id;
      }) : false; // 是否是执行人

      const marketId = this.detailInfo ? this.detailInfo.clientInfo.marketId : '';
      const isSales = marketId === this.userInfo.id; // 是否销售

      let departmentAuth = false; // 拥有部门全向编辑，当前登录的用户存在该条订单的部门中,或者协作部门中
      const isNoOperator = !orderOperator || orderOperator.length === 0;
      if (isNoOperator) {
        const currentDeptIds = this.userInfo.currentDeptIds || []; // 当前部门的所有id，比如：用户部门是 研发部->产品组，那么当前部门就是产品组
        const topDeptIds = this.userInfo.topDeptIds || []; // 顶级部门的id列表，比如：用户部门是 研发部->产品组，那么顶级部门就是研发部

        const departmentAry = currentDeptIds.concat(topDeptIds);
        departmentAuth = departmentAry.some(i => {
          return (departmentId === i) || cooperationDepartmentIds.includes(i);
        });
      }
      return (isOperatorAuth || isSales || departmentAuth || this.isAllAdmin) && hasRouteAuth('crm:orderList:publish');
    },
    tableData() {
      const publishDataList = {
        publishUrl: '',
        publishRemark: '',
        attachment: [],
        createTime: '',
        publishData: {}
      };
      if (this.detailInfo && this.detailInfo.publishInfo) {
        return [this.detailInfo.publishInfo || publishDataList];
      }
      return [publishDataList];
    },
    listSetting() {
      const extendParams = {
        orderId: this.orderInfo.orderId || '', type: 1
      };
      const isRequired = typeof this.isLinkRequired !== undefined ? this.isLinkRequired : (this.orderInfo.resourceType === 0 && this.orderStatus === 1 && !(this.orderInfo.orderPlatform === '小红书' && ['直播坑位', '单条策划'].includes(this.orderInfo.orderForm)));
      return [
        { label: '发布链接', type: 'inputText', prop: { width: '250px' }, maxlength: 500, placeholder: '请输入链接', headerCheck: 'autoPick', headerCheckLabel: '采集数据', width: '160px', isRequired, keyword: 'publishUrl' },
        { label: '发布文案', type: 'inputTextarea', prop: { width: '200px' }, maxlength: 500, keyword: 'publishRemark' },
        { label: '发布截图', type: 'attachment', prop: { width: '200px' }, keyword: 'attachment', extendParams, importApi: '/common/file/upload' },
        { label: '发布数据', type: 'publishData', prop: { minWidth: '300px' }, keyword: 'publishData', placeholder: '输入链接自动获取' },
        { label: '发布时间', type: 'createTime', prop: { minWidth: '160px' }, keyword: 'createTime', placeholder: '输入链接自动获取' },
        { label: '采集有效时间', type: 'createTime', prop: { minWidth: '160px' }, keyword: 'pickTime', placeholder: '输入链接自动获取' }
      ];
    }
  },
  watch: {
    'orderInfo': {
      handler(val) {
        this.handleCheckLinkrequired();
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    getParams() {
      const params = _.cloneDeep(this.tableData[0]);
      params.autoPick = this.detailInfo.publishInfo.autoPick;
      return params;
    },
    handleCheckLinkrequired() {
      const { orderFormId, orderPlatformId, orderSource } = this.orderInfo;
      if (orderFormId && orderPlatformId) {
        const params = {
          orderFormId,
          orderPlatformId
        };
        linkRequiredCheck(params).then(res => {
          if (res.code === 200) {
            this.isLinkRequired = orderSource === 2 ? false : res.data.isRequired;
            this.$emit('setIsLinkRequired', this.isLinkRequired);
          }
        }).catch(err => console.error(err));
      }
    },
    validateForm(validate = true, index = 0) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.simpleEditTableRef.validate().then(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject(index);
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    getOrderInfo() {
      return {
        orderInfo: this.detailInfo.orderInfo,
        type: 'detail'
      };
    },
    handleCheckLink() {
      if (!this.detailInfo || !this.detailInfo.publishInfo) {
        return;
      }
      const params = {
        link: this.detailInfo.publishInfo.publishUrl,
        platformCategory: this.getOrderInfo() ? this.getOrderInfo().orderInfo.orderPlatformId : 0
      };
      checkLink(params).then(_ => {
      }).catch(err => {
        if (err.code === 502) {
          showModal('请注意：检测到提交的发布链接异常，可能无法采集到数据。请确认后重新提交。', '', {}, true).then(_ => {
          }).catch(_ => {
            this.detailInfo.publishInfo.publishUrl = '';
            this.detailInfo.publishInfo.autoPick = false;
          });
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.detail-row {
  background-color: #fff;
  padding: 24px 24px 0 24px;
  &::v-deep {
    .el-table {
      .is-left {
        padding: 2px 0;
      }
    }
  }
}
</style>

